package com.bilibili.sys.servlet;

import com.bilibili.sys.utils.PageUtils;
import com.bilibili.sys.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author alpha
 * @program: BookSystem
 * @description: 系统公共的Servlet，我们约定客户端提交的请求中的action就是在Servlet中要处理的方法的名称
 * @since 2024-03-26 22:39
 **/

public abstract class BaseServlet extends HttpServlet {
    protected PageUtils pageUtils;
    /**
     * 通过反射的方式调用对象中的action对应的方法
 * @param req 
 * @param resp 
     * @return void
     * @author alpha
     * @since 2024/03/26 22:45 
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取传递的action参数
        String action = req.getParameter("action");
        try{
            //获取当前对象对应的Method对象
            Method method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
            //调用method方法
            //***********！！！！！！！！！！
            method.invoke(this,req,resp);//!!!!!!!!!!!千万千万注意！！！！！！！！！
        }catch (Exception e){
            e.printStackTrace();
            //调用方法执行的时候出现了异常
            //this.list(req,resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);

    }
    //定义增删改查的基础方法
    public void list(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        pageUtils = new PageUtils();
        //查询分页相关的参数
        String ps = req.getParameter("pageSize");
        String pn = req.getParameter("pageNum");
        String key = req.getParameter("key");
        //声明默认的分页参数
        int pageSize = 5;//默认每页显示5条
        int pageNum = 1;//默认第一页
        if(StringUtils.isNotEmpty(ps)){
            pageSize= Integer.parseInt(ps);
        }
        if(StringUtils.isNotEmpty(pn)){
            pageNum = Integer.parseInt(pn);
        }
        if(StringUtils.isNotEmpty(key)){
            //如果查询条件不为空 设置当前页为1
            pageNum = 1;
        }

        pageUtils.setPageNum(pageNum);
        pageUtils.setPageSize(pageSize);
        pageUtils.setKey(key);
    }
    public abstract void saveOrUpdate(HttpServletRequest req, HttpServletResponse resp) throws Exception;
    public abstract void remove(HttpServletRequest req, HttpServletResponse resp) throws Exception;
    public abstract void findById(HttpServletRequest req, HttpServletResponse resp) throws Exception;
    public abstract void saveOrUpdatePage(HttpServletRequest req, HttpServletResponse resp) throws Exception;

}
